package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.MqConstants;
import com.example.dto.*;
import com.example.entity.Order;
import com.example.entity.OrderEvaluation;
import com.example.entity.OrderItem;
import com.example.entity.User;
import com.example.entity.enums.EvaluationStatusEnum;
import com.example.entity.enums.OrderStatusEnum;
import com.example.event.OrderCloseEvent;
import com.example.event.publisher.EventPublisher;
import com.example.exception.NoStockException;
import com.example.mapper.OrderItemMapper;
import com.example.mapper.OrderMapper;
import com.example.param.OrderSearchParams;
import com.example.service.*;
import com.example.util.BeanCopyPropertiesUtils;
import com.example.util.RedisUtil;
import com.example.vo.*;
import com.example.vo.buyer.CartGroupedByStoreVo;
import com.example.vo.buyer.CartItemVo;
import com.google.common.reflect.TypeToken;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.constant.RedisConstance.USER_ORDER_TOKEN_PREFIX;

/**
* @author circle48
* @description 针对表【order(订单)】的数据库操作Service实现
* @createDate 2024-05-13 20:15:55
*/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private SkuService skuService;

    @Resource
    private CartInfoService cartInfoService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private EventPublisher eventPublisher;
    @Resource
    private OrderCloseEvent orderCloseEvent;

    @Resource
    private UserCouponService userCouponService;

    @Autowired
    private PaymentInfoService paymentInfoService;


    @Resource
    private UserMessageService userMessageService;


    @Resource
    private UserService userService;

    @Resource
    private CouponService couponService;



    @Autowired
    private OrderEvaluationService orderEvaluationService;

    /**
     * 获取用户的订单和订单项的详细信息，并根据订单状态和商品名称进行筛选
     *
     * @param userId 用户id
     * @param params
     * @return 分页的订单视图对象
     */

    @Override
    public Result getMyOrders(long userId, OrderSearchParams params) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        // 根据订单状态添加查询条件
        if (params.getOrderStatus() != null && !"ALL".equals(params.getOrderStatus())) {
            OrderStatusEnum orderStatusEnum = OrderStatusEnum.valueOf(params.getOrderStatus());
            if (orderStatusEnum != null) {
                queryWrapper.eq(Order::getStatus, orderStatusEnum.getValue());
            }
        }

        // 根据商品名称添加查询条件
        if (params.getProductName() != null && !params.getProductName().isEmpty()) {
            //获取所有包含商品名称的OrderItem的订单ID
            List<Long> orderIds = getOrderIdsByProductName(params.getProductName(), userId);
            if (!orderIds.isEmpty()) {
                queryWrapper.in(Order::getId, orderIds);
            } else {
                // 如果没有订单包含该商品名称，则返回空的结果
                return Result.ok(new PageVo(Collections.emptyList(), 0L));
            }
        }
        // 添加按时间排序条件，最新的订单放前面
        queryWrapper.orderByDesc(Order::getCreateTime);

        // 分页查询订单
        Page<Order> page = new Page<>(params.getPageNum(), params.getPageSize());
        // 执行查询
        orderMapper.selectPage(page, queryWrapper);
        // 将Order对象封装为OrderSimpleVO对象
        List<OrderSimpleVO> orderSimpleVOList = toOrderListVo(page.getRecords());
        // 构建分页VO
        PageVo pageVo = new PageVo(orderSimpleVOList, page.getTotal());

        return Result.ok(pageVo);
    }

    private List<OrderSimpleVO> toOrderListVo(List<Order> list) {
        List<OrderSimpleVO> orderSimpleVOs = BeanCopyPropertiesUtils.copyBeanList(list, OrderSimpleVO.class);
        //遍历Vo集合
        orderSimpleVOs.forEach(orderSimpleVO -> {
            // 获取并设置对应的OrderItemVO列表
            List<OrderItemVO> orderItemVOList =getChildren(orderSimpleVO.getId());
            orderSimpleVO.setOrderItems(orderItemVOList);
            // 将订单状态值转换为文字描述
            orderSimpleVO.setOrderStatus(orderSimpleVO.getStatus().getDesc());
        });
        return orderSimpleVOs;
    }

    /**
     * 根据订单ID查询对应OrderItem集合
     *
     * @param id
     * @return
     */
    private List<OrderItemVO> getChildren(Long id) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, id);
        List<OrderItem> list = orderItemService.selectList(queryWrapper);
        return BeanCopyPropertiesUtils.copyBeanList(list, OrderItemVO.class);
    }

    /**
     * 根据商品名称查询包含该商品名称的所有OrderItem的订单ID
     *
     * @param productName 商品名称
     * @param userId
     * @return 订单ID列表
     */
    private List<Long> getOrderIdsByProductName(String productName, long userId) {
        // MyBatis 使用 % 通配符进行 LIKE 操作，所以你需要在商品名称周围添加 %
        String searchPattern = "%" + productName + "%";
        return orderItemMapper.selectOrderIdsByProductNameAndUser(searchPattern, userId);
    }

    @Override
    @Transactional
    public SubmitOrderResponseVo createOrder(TradeDTO trade) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);

        // 1. 验证防重令牌
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User u = loginUser.getUser();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = stringRedisTemplate.execute(
                new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(USER_ORDER_TOKEN_PREFIX + ":" + String.valueOf(u.getId())),
                trade.getOrderToken()
        );

        if (execute == 0L) {
            // 1.1 防重令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {

            // 2. 创建订单、订单项
            List<OrderCreateDTO> orders = createOrders(u, trade);

            // 3. 验价
            BigDecimal frontEndAmount = BigDecimal.ZERO;
            if(trade.getType() == null || trade.getType() == 1){
                BigDecimal calculatedAmount = cartInfoService.calculateTotalPriceFromRedis(u.getId());
                frontEndAmount = trade.getFlowPrice();
                if (Math.abs(frontEndAmount.subtract(calculatedAmount).doubleValue()) >= 0.01) {
                    responseVo.setCode(2); // 价格验证失败
                    return responseVo;
                }
            }else if(trade.getType() == 2){
                frontEndAmount = trade.getFlowPrice();
            }

            try {
                // 4. 锁定库存
                lockStock(orders);

                // 5. 保存订单和订单项，并更新优惠券状态
                saveOrderAndItems(orders);

                // 6. 发送延迟消息
                sendOrderCloseMessage(orders);
                // 7.更新信息
                sendIntegrationMessage(orders,u);
                // 8. 删除购物车里的数据
                if(trade.getType() == null || trade.getType() == 1){
                    for (OrderCreateDTO orderCreateDTO : orders) {
                        for (OrderItem orderItem : orderCreateDTO.getOrderItems()) {
                            cartInfoService.deleteItemBySkuId(u.getId(), orderItem.getSkuId());
                        }
                    }
                }
                // 设置响应对象
                responseVo.setOrders(orders.stream().map(OrderCreateDTO::getOrder).collect(Collectors.toList()));
                frontEndAmount = frontEndAmount.setScale(2, RoundingMode.HALF_UP);
                responseVo.setTotalPrice(frontEndAmount);

            } catch (NoStockException e) {
                responseVo.setCode(3); // 库存不足
                return responseVo;
            } catch (Exception e) {
                responseVo.setCode(4); // 其他异常
                return responseVo;
            }
        }
        return responseVo;
    }

    @Override
    public void updataUserIntegration(String out_trade_no) {
        // 通过订单号找到对应的订单，并更新状态为已支付
        String orderIds = paymentInfoService.getOrderIds(out_trade_no);
        String[] ids = orderIds.split(",");
        int totalPoints = 0;
        // 创建 Map 用于存储 orderId 和 userId 的对应关系
        Map<Long, Long> orderIdToUserIdMap = new HashMap<>();
        for (String orderId : ids) {
            Long orderIdLong = Long.parseLong(orderId.trim());
            Order order = baseMapper.selectById(orderIdLong);
            if (order != null) {
                // 获取订单对应的订单项列表
                List<OrderItem> orderItems = orderItemService.getByOrderId(orderIdLong);
                // 计算订单项的积分总和
                int orderItemPoints = orderItems.stream()
                        .mapToInt(OrderItem::getGiftIntegration) // 获取订单项的积分
                        .sum();
                totalPoints += orderItemPoints;
            }
            // 获取订单对应的用户ID，并存储到 Map 中
            orderIdToUserIdMap.put(orderIdLong, order.getUserId());
        }
        // 获取订单对应的用户ID，并更新用户积分
        for (Long orderId : orderIdToUserIdMap.keySet()) {
            Long userId = orderIdToUserIdMap.get(orderId);
            User u = userService.getById(userId);
            userService.updataUserIntegration(totalPoints, u);
        }
    }

    private void sendIntegrationMessage(List<OrderCreateDTO> orders,User u) {
        int totalPoints = 0;
        for (OrderCreateDTO order : orders) {
            for (OrderItem item : order.getOrderItems()) {
                totalPoints += item.getGiftIntegration();
            }
        }
        userMessageService.publishIntegrationMessage(totalPoints, u);
    }

    public void sendOrderCloseMessage(List<OrderCreateDTO> orders) {

        eventPublisher.publish(MqConstants.Exchange.ORDER_EXCHANGE, MqConstants.Key.ORDER_DELAY_KEY, orderCloseEvent.buildEventMessage(orders), 10 * 60 * 1000);
    }



    private List<OrderCreateDTO> createOrders(User u, TradeDTO trade) {
        return trade.getOrders().stream()
                .map(orderDTO -> {
                    String orderSn = IdWorker.getTimeId();

                    // 构建订单
                    Order order = buildOrder(u, trade, orderDTO, orderSn);

                    // 构建订单项
                    List<OrderItem> orderItems = buildOrderItems(orderDTO.getItems(), orderSn);
                    // 计算订单价格
                    compute(order, orderItems);
                    // 保存订单和订单项
                    OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
                    orderCreateDTO.setOrder(order);
                    orderCreateDTO.setOrderItems(orderItems);

                    return orderCreateDTO;
                })
                .collect(Collectors.toList());
    }

    private void saveOrderAndItems(List<OrderCreateDTO> orderCreateDTOs) {
        orderCreateDTOs.forEach(orderCreateDTO -> {
            Order order = orderCreateDTO.getOrder();
            LocalDateTime now = LocalDateTime.now();
            order.setCreateTime(now);
            order.setModifyTime(now);

            // 保存订单，并确保获得生成的订单ID
            this.baseMapper.insert(order);
            Long orderId = order.getId(); // 获取自动生成的ID


            // 更新订单项的orderId，并清除手动设置的id
            List<OrderItem> orderItems = orderCreateDTO.getOrderItems();
            orderItems.forEach(orderItem -> {
                orderItem.setOrderId(orderId);
                orderItem.setId(null); // 清除手动设置的主键id
            });

            // 保存订单项
            orderItemService.saveBatch(orderItems);

            // 更新优惠券状态
            updateCouponStatus(order);
        });
    }

    private void updateCouponStatus(Order order) {
        String couponIds = order.getCouponIds();
        log.info("couponIds:{}", couponIds);
        if (couponIds != null && !couponIds.isEmpty()) {
            String[] couponIdArray = couponIds.split(",");
            for (String couponIdStr : couponIdArray) {
                Long couponId = Long.valueOf(couponIdStr);
                userCouponService.updateCouponStatusToUsed(couponId, order.getId(), order.getOrderSn());
                UserCouponVO vo = userCouponService.getCouponsById(couponId);
                couponService.updateUseCount(vo.getCouponId());
            }
        }
    }




    private Order buildOrder(User u, TradeDTO trade, OrderDTO orderDTO, String orderSn) {
        // 使用工具类进行属性拷贝
        Order order = BeanCopyPropertiesUtils.copyBean(orderDTO, Order.class);

        // 手动设置需要单独处理的字段
        order.setOrderSn(orderSn);
        order.setUserId(u.getId());
        order.setUserName(u.getUsername());

        // 设置收货地址信息
        order.setReceiverName(trade.getReceiverName());
        order.setReceiverPhone(trade.getReceiverPhone());
        order.setReceiverProvince(trade.getReceiverProvince());
        order.setReceiverCity(trade.getReceiverCity());
        order.setReceiverRegion(trade.getReceiverRegion());
        order.setReceiverDetailAddress(trade.getReceiverDetailAddress());

        // 设置订单相关状态信息
        order.setStatus(OrderStatusEnum.WAIT_PAY);
        order.setConfirmStatus(0);

        // 设置商家信息
        order.setStoreId(orderDTO.getStoreId());
        order.setStoreName(orderDTO.getStoreName());

        return order;
    }



    private List<OrderItem> buildOrderItems(List<OrderItemDTO> orderItemDTOs, String orderSn) {
        return orderItemDTOs.stream()
                .map(orderItemDTO -> {
                    OrderItem orderItem = buildOrderItem(orderItemDTO);
                    orderItem.setOrderSn(orderSn); // 设置订单号
                    return orderItem;
                })
                .collect(Collectors.toList());
    }


    private OrderItem buildOrderItem(OrderItemDTO item) {
        // 使用工具类进行属性拷贝
        OrderItem orderItemEntity = BeanCopyPropertiesUtils.copyBean(item, OrderItem.class);


        // 商品的积分成长，为价格x数量
        orderItemEntity.setGiftGrowth(item.getSkuPrice().multiply(new BigDecimal(item.getSkuQuantity())).intValue());
        orderItemEntity.setGiftIntegration(item.getSkuPrice().multiply(new BigDecimal(item.getSkuQuantity())).intValue());

        // 订单项订单价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);

        // 检查 couponAmount 是否不为空，如果为空则设置为 0
        if (item.getCouponAmount() != null) {
            orderItemEntity.setCouponAmount(item.getCouponAmount());
        } else {
            orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        }
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        // 实际价格
        BigDecimal originalPrice = item.getSkuPrice();

        // 实际价格
        BigDecimal realPrice = item.getRealAmount();

        // 如果realPrice不为null，则使用realPrice，否则使用原价
        orderItemEntity.setRealAmount(realPrice != null ? realPrice : originalPrice);

        return orderItemEntity;
    }


    private void compute(Order entity, List<OrderItem> orderItemEntities) {
        //总价
        BigDecimal total = BigDecimal.ZERO;
        //优惠价格
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        //积分
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        for (OrderItem orderItemEntity : orderItemEntities) {
            total=total.add(orderItemEntity.getRealAmount());
            promotion=promotion.add(orderItemEntity.getPromotionAmount());
//            integration=integration.add(orderItemEntity.getIntegrationAmount());
            coupon=coupon.add(orderItemEntity.getCouponAmount());
            integrationTotal += orderItemEntity.getGiftIntegration();
            growthTotal += orderItemEntity.getGiftGrowth();
        }

        entity.setTotalAmount(total);
        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integration);
        entity.setCouponAmount(coupon);
        entity.setIntegration(integrationTotal);
        entity.setGrowth(growthTotal);

        //付款价格=商品价格+运费
        entity.setPayAmount(entity.getFreightAmount().add(total));

        //设置删除状态(0-未删除，1-已删除)
        entity.setDeleteFlag(0);
    }

    private void lockStock(List<OrderCreateDTO> orderCreateDTOs) throws NoStockException {
        for (OrderCreateDTO orderCreateDTO : orderCreateDTOs) {
            for (OrderItem orderItem : orderCreateDTO.getOrderItems()) {
                skuService.lockStock(orderItem.getSkuId(), orderItem.getSkuQuantity());
            }
        }
    }


    @Override
    public List<OrderItemDTO> getOrderList(Long userId) {
        String redisKey = "user:" + userId + ":cart";
        Object cachedCart = redisUtil.get(redisKey);
        if (cachedCart instanceof List) {
            List<CartGroupedByStoreVo> cartGroupedByStoreVos = (List<CartGroupedByStoreVo>) cachedCart;
            List<OrderItemDTO> orderItems = new ArrayList<>();
            for (CartGroupedByStoreVo cartGroup : cartGroupedByStoreVos) {
                for (CartItemVo cartItem : cartGroup.getItems()) {
                    if (cartItem.getCheck() == 1) {
                        OrderItemDTO orderItem = BeanCopyPropertiesUtils.copyBean(cartItem, OrderItemDTO.class);
                        orderItem.setSkuPic(cartItem.getSkuImage());
                        orderItem.setSkuQuantity(cartItem.getCount());
                        orderItem.setStoreId(cartGroup.getStoreId());
                        orderItems.add(orderItem);
                    }
                }
            }
            return orderItems;
        }
        return Collections.emptyList();
    }


    @Override
    public void closeOrder(List<OrderCreateDTO> orders) {
        for (OrderCreateDTO orderCreateDTO : orders) {
            Long orderId = orderCreateDTO.getOrder().getId();

            // 查询最新的订单
            Order newOrderEntity = this.getById(orderId);

            // 如果订单还处于新创建的状态，说明超时未支付，进行关单
            if (newOrderEntity.getStatus() == OrderStatusEnum.WAIT_PAY) {
                log.info("关闭订单");
                Order updateOrder = new Order();
                updateOrder.setId(newOrderEntity.getId());
                updateOrder.setStatus(OrderStatusEnum.CLOSED);
                this.updateById(updateOrder);
            }
        }


    }


    @Override
    public void updateOrderStatus(String out_trade_no) {
        // 通过订单号找到对应的订单，并更新状态为已支付
        String orderIds = paymentInfoService.getOrderIds(out_trade_no);
        String[] ids = orderIds.split(",");
        for (String orderId : ids) {
            Order order = baseMapper.selectById(Long.parseLong(orderId.trim()));
            if (order != null) {
                order.setStatus(OrderStatusEnum.WAIT_ROG);
                order.setPayType(1);
                order.setPaymentTime(LocalDateTime.now());
                baseMapper.updateById(order);
            }
        }
    }


    @Override
    public Result<List<AdminOrderDto>> getOrderList() {
        List<AdminOrderDto> orderList = orderMapper.getOrderList();
        for (AdminOrderDto orderDto : orderList) {
            orderDto.convertStatusDesc();
            orderDto.convertPayDesc();
        }
        return Result.ok(orderList);
    }

    @Override
    public Result<List<AdminOrderDto>> searchOrderList(SearchOrderDto searchOrderDto) {
        List<AdminOrderDto> orderList = orderMapper.searchOrderList(searchOrderDto);
        for (AdminOrderDto orderDto : orderList) {
            orderDto.convertStatusDesc();
            orderDto.convertPayDesc();
        }
        return Result.ok(orderList);
    }

    @Override
    public Result<AdminOrderDetail> getOrderDetail(String orderSn){
        ModelMapper modelMapper = new ModelMapper();
        Order orderInfo = orderMapper.getOrderDetail(orderSn);
        if (orderInfo == null) {
            return Result.error("订单不存在");
        }
        List<OrderItem> orderItems = orderItemMapper.getProductsByOrderSn(orderInfo.getId());
        if (orderItems == null || orderItems.isEmpty()) {
            return Result.error("订单项不存在");
        }

        AdminOrderDetail adminOrderDetail = modelMapper.map(orderInfo, AdminOrderDetail.class);
        List<ProductDto> productDtos = modelMapper.map(orderItems, new TypeToken<List<ProductDto>>(){}.getType());
        adminOrderDetail.setProducts(productDtos);
        return Result.ok(adminOrderDetail);
    }


    @Override
    public List<Order> getOrdersToAutoConfirm() {
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        Date deliveryTime = Date.from(sevenDaysAgo.atZone(ZoneId.systemDefault()).toInstant());

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getStatus, OrderStatusEnum.WAIT_RECEIVE)
                .le(Order::getDeliveryTime, deliveryTime);

        return orderMapper.selectList(queryWrapper);
    }

    @Override
    public void confirmReceipt(Long id) {
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Order::getStatus, OrderStatusEnum.COMPLETE)
                .set(Order::getConfirmStatus, 1)
                .set(Order::getReceiveTime, new Date())
                .eq(Order::getId, id);

        orderMapper.update(null, updateWrapper);
        // 获取订单详情
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("id", id));
        if (order != null) {
            // 使用工具类进行属性拷贝
            OrderEvaluation evaluation = BeanCopyPropertiesUtils.copyBean(order, OrderEvaluation.class);

            // 设置其他字段
            evaluation.setCreateBy(order.getUserName());
            evaluation.setCreateTime(LocalDateTime.now());
            evaluation.setDeleteFlag(false);
            evaluation.setUpdateBy(order.getUserName());
            evaluation.setUpdateTime(LocalDateTime.now());
            evaluation.setContent(""); // 评价内容由用户填写，暂时为空
            evaluation.setStatus(EvaluationStatusEnum.UN_EVALUATED); // 未评价
            evaluation.setReplyStatus(false);

            // 调用 OrderEvaluationService 进行插入操作
            orderEvaluationService.save(evaluation);
        }
    }



    @Override
    public List<Order> findByOrderSn(String outTradeNo) {
        return this.list(Wrappers.<Order>lambdaQuery().eq(Order::getOrderSn, outTradeNo));
    }


    @Override
    public void handlePaymentCancellation(String outTradeNo) {
        String orderIds = paymentInfoService.getOrderIds(outTradeNo);
        String[] ids = orderIds.split(",");
        List<Order> orders = new ArrayList<>();

        for (String orderId : ids) {
            Order order = baseMapper.selectById(Long.parseLong(orderId.trim()));
            if (order != null) {
                orders.add(order);
            }
        }

        if (!orders.isEmpty()) {
            // 发送支付提醒消息
            Long userId = orders.get(0).getUserId(); // 假设所有订单属于同一用户
            User user = userService.getById(userId);
            if (user != null) {
                userMessageService.sendPaymentReminder(user, orders);
            }
        }
    }


    @Override
    public Order getBySn(String orderSn) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderSn, orderSn);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public void receiving(String orderSn) {
        //修改订单状态为完成
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Order::getStatus, OrderStatusEnum.COMPLETE)
                .set(Order::getConfirmStatus, 1)
                .set(Order::getReceiveTime, new Date())
                .eq(Order::getOrderSn, orderSn);

        orderMapper.update(null, updateWrapper);
        // 获取订单详情
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_sn", orderSn));
        if (order != null) {
            // 获取订单项
            List<OrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_sn", orderSn));
            if (orderItems != null && !orderItems.isEmpty()) {
                // 对每个订单项创建对应的OrderEvaluation
                for (OrderItem orderItem : orderItems) {
                    OrderEvaluation evaluation = BeanCopyPropertiesUtils.copyBean(order, OrderEvaluation.class);
                    evaluation.setId(null);
                    evaluation.setGoodsId(orderItem.getSpuId());
                    evaluation.setGoodsName(orderItem.getSkuName());
                    evaluation.setGoodsImage(orderItem.getSkuPic());
                    evaluation.setOrderItemId(orderItem.getId());
                    evaluation.setSkuId(orderItem.getSkuId());

                    // 设置其他字段
                    evaluation.setCreateBy(order.getUserName());
                    evaluation.setCreateTime(LocalDateTime.now());
                    evaluation.setDeleteFlag(false);
                    evaluation.setUpdateBy(order.getUserName());
                    evaluation.setUpdateTime(LocalDateTime.now());
                    evaluation.setContent(""); // 评价内容由用户填写，暂时为空
                    evaluation.setStatus(EvaluationStatusEnum.UN_EVALUATED); // 未评价
                    evaluation.setReplyStatus(false);

                    // 调用 OrderEvaluationService 进行插入操作
                    orderEvaluationService.save(evaluation);
                }
            }
        }
    }

    @Override
    public List<Order> getSellerOrderList(Long storeId) {
        return baseMapper.getSellerOrderList(storeId);
    }

    @Override
    public void updateOrder(ImportOrderDto testDto){
        baseMapper.updateOrder(testDto);
    }
}




